#pragma once


#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <functional>
#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

static const int g_sockfd = -1;
static const in_port_t g_localport = 8888;

enum
{
    SOCKET_ERROR = 1, 
    BIND_ERROR
};

using func_t = std::function<const std::string(const std::string&)>;


class UdpServer : public nocopy
{
private:
public:
    UdpServer(func_t func, in_port_t localport = g_localport)
        : _func(func), _sockfd(g_sockfd), _localport(localport), _isrunning(false)
    {}

    void InitServer()  // 初始化服务器 
    {
        // 创建 套接字 -> socket 文件 
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket() -> socket error, errno: %d -> %s\n", errno, strerror(errno));
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd: %d\n", _sockfd); // 3 

        // 绑定套接字（IP 地址、端口号） 
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;          // 16 位地址类型，表示 IPv4 网络通信，告诉 OS 这是一个 IPv4 地址 
        local.sin_port = htons(_localport);  // 有网络字节序的问题，所以需要 主机序列（h） 转 网络序列（n） 
        // local.sin_addr.s_addr = inet_addr(_localip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;  // INADDR_ANY 表示任意网络地址，所以服务器端进行任意 IP 地址绑定 

        // 将上面的网络信息绑定进内核中 
        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof local);
        if (n < 0)
        {
            LOG(FATAL, "bind() -> bind error, errno: %d -> %s\n", errno, strerror(errno));
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind success\n");
    }

    void Start()  // 启动服务器 
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            ssize_t n = recvfrom(_sockfd, inbuffer, (sizeof inbuffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                inbuffer[n] = 0;
                std::cout << "[" << addr.GetIP() << ":" << addr.GetPort() << "]# " << inbuffer << std::endl;

                // 获取一个一个的单词 
                std::string result = _func(inbuffer);
                
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len);
            }
        }
    }

    ~UdpServer()
    {
        if (_sockfd > g_sockfd) ::close(_sockfd);
    }

private:
    int _sockfd;
    in_port_t _localport;
    // std::string _localip;
    bool _isrunning;

    func_t _func;
};

